package com.haiyou.common.util;

import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Component
public class RequestUtils {

    /**
     * 获取HttpServletRequest
     */
    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    /**
     * HttpServletResponse
     * @return
     */
    public static HttpServletResponse getResponse(){
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }

    public static HashMap<String,Object> getParams(HttpServletRequest request){
        Map<String, String[]> parameterMap = request.getParameterMap();
        HashMap<String,Object> params=new HashMap<>();
        if (null!=parameterMap&&parameterMap.size()>0){
            parameterMap.forEach((k,v)-> params.putIfAbsent(k,v[0]));
        }
        return params;
    }

    public static HashMap<String,Object> getParams(){
        HttpServletRequest request = getRequest();
        Map<String, String[]> parameterMap = request.getParameterMap();
        HashMap<String,Object> params=new HashMap<>();
        if (null!=parameterMap&&parameterMap.size()>0){
            parameterMap.forEach((k,v)-> params.putIfAbsent(k,v[0]));
        }
        return params;
    }
}
